import { useLocalStorageState, useMemoizedFn } from "ahooks";
import { createContainer } from "unstated-next";
import { PICK_APPS } from "../config/minapps";
import { useMemo } from "react";
import { useDragAndDrop } from "@formkit/drag-and-drop/react";

export const websiteStore = createContainer(() => {
  const [activeKey, setActiveKey] = useLocalStorageState("app-active", {
    defaultValue: "moonshot",
  });
  const [website, setWebsite] = useLocalStorageState("app-website1", {
    defaultValue: PICK_APPS,
  });

  const [ref, list, setList] = useDragAndDrop(website, {
    group: "ref",
    onDragend(data) {
      setWebsite(data.values);
    },
  });

  const addWebsite = useMemoizedFn((item) => {
    let prev = [...website];
    prev = prev.some((a) => a.id === item.id) ? prev : [...prev, item];
    setWebsite(prev);
    setList(prev);
    setActiveKey(item.id);
  });
  const removeWebsite = useMemoizedFn((item) => {
    let prev = [...website];
    if (prev.length === 1) {
      return;
    }
    prev = prev.filter((i) => i.id !== item.id);
    setWebsite(prev);
    setList(prev);
    if (activeKey === item.id) {
      setActiveKey(prev[0].id);
    }
  });

  const active = useMemo(() => {
    return website.find((i) => i.id === activeKey) || website[0];
  }, [activeKey, website]);

  return {
    ref,
    active,
    activeKey,
    setActiveKey,
    website: list,
    addWebsite,
    removeWebsite,
  };
});
